package com.mj.mafeed.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.mj.mafeed.R;
import com.mj.mafeed.bean.CartItemJSON;
import com.mj.mafeed.bean.ProductJSON;
import com.mj.mafeed.config.Constants;
import com.mj.mafeed.service.CartItemService;
import com.mj.mafeed.service.FavoriteService;
import com.mj.mafeed.service.ProductService;
import com.mj.mafeed.swipeback.SwipeBackActivity;
import com.mj.mafeed.util.NetUtils;
import com.mj.mafeed.util.SPUtils;
import com.mj.mafeed.widget.LoadingDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

/**
 * 产品详情
 * @author zhaominglei
 * @date 2014-12-7
 * 
 */
public class ProductDetailActivity extends SwipeBackActivity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = ProductDetailActivity.class.getSimpleName();
	private CartItemService cartItemService = new CartItemService();
	private FavoriteService favoriteService = new FavoriteService();
	private ImageView goHome;
	private ImageView productImage;
	private TextView productName;
	private TextView productPrice;
	private TextView productMemo;
	private ImageLoader imageLoader = null;
	private DisplayImageOptions options = null;
	private WebView productWebView;

	private Button productAddCart;
	private Button productCart;
	private Button productAddFavorite;
	private Button productBook;
	private LoadingDialog loadingDialog;
	private ProgressBar progressBar;
	
	private long productId; //商品id
	private ProductJSON productJSON; //商品详情
	private String referer; //来自那个链接
	private String username; //用户名
	private String sign; //签名
	@SuppressWarnings("unused")
	private String keyword; //关键词
	private Intent intent;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_product_detail);
		
		init();
	}
	
	@SuppressWarnings("deprecation")
	@SuppressLint("SetJavaScriptEnabled")
	public void init() {
		goHome = (ImageView) findViewById(R.id.product_detail_gohome);
		productImage = (ImageView) findViewById(R.id.product_detail_image);
		productName = (TextView) findViewById(R.id.product_detail_template_name);
		productPrice = (TextView) findViewById(R.id.product_detail_template_price);
		productMemo = (TextView) findViewById(R.id.product_detail_template_memo);
		productAddFavorite = (Button) findViewById(R.id.product_detail_add_favorite);
		productAddCart = (Button) findViewById(R.id.product_detail_add_cart);
		productCart = (Button) findViewById(R.id.product_detail_cart);
		productBook = (Button)findViewById(R.id.product_detail_book);
		productWebView = (WebView) findViewById(R.id.product_detail_webview);
		progressBar = (ProgressBar) findViewById(R.id.product_detail_progressbar);
		
		goHome.setOnClickListener(this);
		productAddFavorite.setOnClickListener(this);
		productAddCart.setOnClickListener(this);
		productCart.setOnClickListener(this);
		productBook.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
		
		productId = getIntent().getLongExtra("productId", 0);
		keyword = getIntent().getStringExtra("keyword");
		referer = getIntent().getStringExtra("referer");
		username = (String)SPUtils.get(getApplicationContext(), "username", "");
		sign = (String)SPUtils.get(getApplicationContext(), "sign", "");
		
		imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		options = new DisplayImageOptions.Builder()
				.displayer(new RoundedBitmapDisplayer(0xff000000, 10))
				.cacheInMemory().cacheOnDisc().build();
		
		WebSettings webSettings = productWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setDefaultTextEncodingName("utf-8");
		
		getProductDetail();		
		setEdgeFromLeft();
		checkFavorite();
	}

	private void getProductDetail() {
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ProductDetailAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.product_detail_gohome:
				ProductDetailActivity.this.finish();
				break;
			
			case R.id.product_detail_add_favorite:
				if (username != null && !username.equals("") && sign != null && !sign.equals("")) {
					addFavorite(getApplicationContext(), v);
				} else {
					Toast.makeText(getApplicationContext(), R.string.check_login_error, Toast.LENGTH_SHORT).show();
				}
				break;
				
			case R.id.product_detail_add_cart:
				addCart(getApplicationContext(), v, productJSON);
				break;
			
			case R.id.product_detail_book:
				intent = new Intent(ProductDetailActivity.this, BookLogActivity.class);
				intent.putExtra("referer", "ProductDetailActivity");
				Bundle bundle = new Bundle();
				bundle.putSerializable("productJSON", productJSON);
				intent.putExtras(bundle);
				startActivity(intent);
				break;
				
			case R.id.product_detail_cart:
				ProductDetailActivity.this.finish();
				break;	
				
			default:
				break;
		}
	}

	@Override
	public void onBackPressed() {
		ProductDetailActivity.this.finish();
	}
	
	private void addCart(Context context, View v, ProductJSON productJSON) {
		CartItemJSON cartItemJSON = cartItemService.getByProductId(context, productJSON.getProductId());
		if (cartItemJSON == null) {
			cartItemJSON = new CartItemJSON();
			cartItemJSON.setProductId(productJSON.getProductId());
			cartItemJSON.setQuantity(1);
			cartItemJSON.setSn(productJSON.getSn());
			cartItemJSON.setName(productJSON.getName());
			cartItemJSON.setPrice(productJSON.getPrice());
			cartItemJSON.setStock(productJSON.getStock());
			cartItemJSON.setImageUrl(productJSON.getImageUrl());
			cartItemService.save(context, cartItemJSON);
		} else {
			cartItemJSON.setQuantity(cartItemJSON.getQuantity()+1);
			cartItemService.update(context, cartItemJSON);
		}
		Toast.makeText(getApplicationContext(), R.string.add_success, Toast.LENGTH_SHORT).show();
	}

	private void addFavorite(Context context, View v) {
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ProductAddFavoriteAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}
	
	private void checkFavorite() {
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ProductCheckFavoriteAsyncTask().execute("");
		}
	}
	
	public class ProductDetailAsyncTask extends AsyncTask<String, String, ProductJSON> {
		@Override
		protected ProductJSON doInBackground(String... params) {
			return new ProductService().getProductDetail(getApplicationContext(), productId);
		}
		@Override
		protected void onPostExecute(ProductJSON result) {
			if (result == null) {
				Toast.makeText(getApplicationContext(), R.string.like_net_error, Toast.LENGTH_SHORT).show();
			}
			progressBar.setVisibility(View.GONE);
			loadingDialog.dismiss();
			if (result != null) {
				productJSON = result;
				productName.setText(result.getName());
				productPrice.setText(String.valueOf(result.getPrice()));
				productMemo.setText(result.getMemo());
				imageLoader.displayImage(Constants.SERVER_DOWNLOAD_URL+result.getImageUrl(), productImage, options);
				productWebView.loadData(result.getIntroduction(), "text/html; charset=utf-8", null);
				productWebView.setVisibility(View.VISIBLE);
				if (productJSON != null && productJSON.getIsSell()) {
					productAddCart.setVisibility(View.VISIBLE);
					productBook.setVisibility(View.GONE);
				} else {
					productAddCart.setVisibility(View.GONE);
					productBook.setVisibility(View.VISIBLE);
				}
			}
		}
		
	}
	
	public class ProductAddFavoriteAsyncTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			return favoriteService.addFavorite(getApplicationContext(), referer, productId);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			loadingDialog.dismiss();
			if (result) {
				Toast.makeText(getApplicationContext(), R.string.add_success, Toast.LENGTH_SHORT).show();
				productAddFavorite.setText(R.string.has_favorited);
			} else {
				Toast.makeText(getApplicationContext(), R.string.add_error, Toast.LENGTH_SHORT).show();
			}
			
		}		
	}
	
	public class ProductCheckFavoriteAsyncTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			return favoriteService.checkFavorite(getApplicationContext(), referer, productId);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			loadingDialog.dismiss();
			if (result) {
				productAddFavorite.setText(R.string.has_favorited);
			}
		}		
	}
}
